package com.zhny.sensor.nio;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

/**
 * @Auther: zhy
 * @Date: 2019/11/14
 * @Description: Socket通讯服务端
 */
@Service
@PropertySource(value = {"classpath:app.properties"})
public class BCMNettyServer {

    @Autowired
    private ServerHandler serverHandler;


    @Value("${netty.port}")
    private int port;

    private static final Logger log = LoggerFactory.getLogger(BCMNettyServer.class);


    /**
     * 初始化netty配置
     */
    public void run() {

        EventLoopGroup bossGroup = new NioEventLoopGroup();  //处理连接的线程池
        EventLoopGroup workerGroup = new NioEventLoopGroup();//处理读取数据的线程池
        try {
            // 1.创建服务类对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            // 2.配置服务端
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128 )
                    .localAddress(port)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //将自定义的handler添加到流水线上——里面编写业务代码
                            socketChannel.pipeline()
                                    .addLast(new DelimiterBasedFrameDecoder(2048,
                                            Unpooled.copiedBuffer(new byte[]{(byte) 0xFC,(byte) 0xFC})))
                                    .addLast("serverHandler", serverHandler);
                        }
                    });

            // 3. 最后绑定服务器等待直到绑定完成，调用sync()方法会阻塞直到服务器完成绑定,
            // 然后服务器等待通道关闭，因为使用sync()，所以关闭操作也会被阻塞。
            // 开启绑定服务端口
            ChannelFuture channelFuture = serverBootstrap.bind().sync();
            log.info("开始监听端口为：" + channelFuture.channel().localAddress());

            // 开启关闭等待
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

}
